#!/usr/bin/python
# Filename: Agent.py

import os
import sys
import time
import platform
import psutil
import socket
import datetime
import urllib2
import urllib
import threading
class Agent:
	"""
	"""
	def __init__(self):
		"""
		"""
		self._infos = {}
	def updateInfos(self):
		"""
		"""
		self._infos["OS"] = platform.system()
		self._infos["NAME"] = platform.node()
		self._infos["CPU_USE"] = psutil.cpu_percent(interval=1)
		self._infos["CPU_USE_PER_CORE"] = psutil.cpu_percent(interval=1, percpu=True)
		cpuTime = psutil.cpu_times_percent(interval=1)
		self._infos["CPU_SYS_REPARTITION"] = {"USER": cpuTime[0],"SYSTEM": cpuTime[1], "IDLE":cpuTime[2]}
		ram = psutil.virtual_memory()
		self._infos["RAM"] = {"TOTAL": int(ram[0]/1024/1024),"AVAILABLE": int(ram[1]/1024/1024),"PERCENT": ram[2],"USED": int(ram[3]/1024/1024)}
		swap = psutil.swap_memory()
		self._infos["SWAP"] = {"TOTAL": int(swap[0]/1024/1024),"USED": int(swap[1]/1024/1024),"PERCENT": ram[2],"FREE": int(ram[3]/1024/1024)}
		disk = psutil.disk_usage('/') 
		self._infos["DISK"] = {"TOTAL": int(disk[0]/1024/1024),"USED": int(disk[1]/1024/1024),"FREE": int(disk[2]/1024/1024),"PERCENT": disk[3]}
		self._infos["USER"] = psutil.get_users()[0][0]
		self._infos["BOOT_TIME"] = datetime.datetime.fromtimestamp(psutil.get_boot_time()).strftime('%Y-%m-%d %H:%M:%S')
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		s.connect(("gmail.com",80))
		self._infos["IP"] = s.getsockname()[0]
		s.close()
		
	def getInfos(self):
		"""
		"""
		return self._infos
	def sendRequest(self, url, params):
		"""
		"""
		try:
			submitUrl = url + '/run'
			postData = urllib.urlencode(params)
			fh = urllib2.urlopen(submitUrl, postData)
			jobId = fh.read()
			fh.close()
		except urllib2.HTTPError, ex:
			# Trap exception and output the document to get error message.
			print >>sys.stderr, ex.read()
			raise
		# Print job identifier
		print jobId
		
